<?php

use Illuminate\Database\Capsule\Manager as DB;

abstract class middlewareModel
{

    /**
     * @api 中间件处理程序
     */
    public abstract function handle($postData);

    /**
     * @api 前端验证登陆标记cookie是否合法
     */
    protected function checkCookie()
    {
        $auth = new Auth(_CookieKey_);
        if (!$auth->isLogin()) {
            throw new Exception('未登陆.', 401);
        }else{
            return $auth;
        }
    }
    /**
     * @api 前端验证登陆标记token是否合法
     */
    protected function checkToken()
    {
        $token = getHeader('Authorization');
        if (empty($token)) {
            if ($token = Yaf_Dispatcher::getInstance()->getRequest()->get('Authorization')) {
            } else {
                throw new Exception('token为空.', 401);
            }
        }
        $user = remember('auth_' . $token, -1, function () use ($token) {
            $user = DB::table('customer')->where('token', $token)->first();
            if (empty($user)) {
                throw new Exception('token无效.', 401);
            }
            $data = [
                'user_id'  => $user->id,
                'username' => $user->username,
                'phone'    => $user->phone,
                'avatar'   => $user->avatar,
                'gender'   => $user->gender,
            ];
            return $data;
        });
        if (!$user) {
            throw new Exception('登陆失败.', 401);
        }
        return $user;
    }

}
